package com.yww.leetcode.queue;

/**
 * @author yww
 * @description 622. 设计循环队列
 * @since 2024/2/4 18:53
 */
public class MyCircularQueue622 {
    Node head;
    Node tail;
    int capacity;
    int size;

    // MyCircularQueue(k): 构造器，设置队列长度为 k 。
    public MyCircularQueue622(int k) {
        this.capacity = k;
        head = new Node(-1, null);
        tail = head;
        tail.next = head;
    }

    // enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
    public boolean enQueue(int value) {
        if (isFull()) {
            return false;
        }
        Node added = new Node(value, head);
        tail.next = added;
        tail = added;
        size++;
        return true;
    }

    // deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
    public boolean deQueue() {
        if (isEmpty()) {
            return false;
        }
        Node first = head.next;
        if (first.next == head) {
            tail = head;
        }
        head.next = first.next;
        size--;
        return true;
    }

    // Front: 从队首获取元素。如果队列为空，返回 -1
    public int Front() {
        if (isEmpty()) {
            return -1;
        }
        return head.next.val;
    }

    // Rear: 获取队尾元素。如果队列为空，返回 -1 。
    public int Rear() {
        if (isEmpty()) {
            return -1;
        }
        return tail.val;
    }

    public boolean isEmpty() {
        return head == tail;
    }

    public boolean isFull() {
        return size == capacity;
    }

    private class Node {
        int val;
        Node next;

        public Node(int val, Node next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        MyCircularQueue622 queue = new MyCircularQueue622(6);
        System.out.println(queue.enQueue(6));
        System.out.println(queue.Rear());
        System.out.println(queue.Rear());
        System.out.println(queue.deQueue());
        System.out.println(queue.enQueue(5));
        System.out.println(queue.Rear());
        System.out.println(queue.deQueue());
        System.out.println(queue.Front());
        System.out.println(queue.deQueue());
        System.out.println(queue.deQueue());
        System.out.println(queue.deQueue());
    }
}
